package beautiful.butterfly.server.httpserver.mvc.render;

import beautiful.butterfly.server.application.Application;
import beautiful.butterfly.server.application.Environment;
import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

public class VelocityRender extends Render {


    String velocityPagePath;

    public VelocityRender(String velocityPagePath) {
        this.velocityPagePath = velocityPagePath;
    }

    @Override
    public String render() {

        String path = Environment.pathFix(ActionContext.getHttpServer().getTemplatesPath() + velocityPagePath);
        File file = new File(path);
        Properties properties = new Properties();
        properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, file.getParentFile().getPath());
        properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");

        VelocityEngine velocityEngine = new VelocityEngine(properties);
        VelocityContext velocityContext = new VelocityContext();
        Map<String, Object> map = ActionContext.getRequest().getAttributeMap();
        for (String key : map.keySet()) {
            velocityContext.put(key, map.get(key));
            if (Application.developMode) {
                System.out.println("返回信息:key:" + key + ",value:" + map.get(key));
            }
        }
        StringWriter stringWriter = new StringWriter();
        velocityEngine.mergeTemplate(file.getName(), "utf-8", velocityContext, stringWriter);

        return stringWriter.toString();
    }
}
